﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EkspSys.Map;
using System.Net;
using System.Net.Sockets;
using EkspSys.Network;

namespace EkspSys
{
    public partial class EndPointInfoForm : Form
    {
        private EndPointInfo info;

        public delegate void TraceRouteDelegate(IPAddress addr);
        public event TraceRouteDelegate TraceRouteEvent;

        public EndPointInfoForm(EndPointInfo info)
        {
            InitializeComponent();

            this.info = info;

            addressLbl.Text = info.Address.ToString();
            locationLbl.Text = info.Location.city + ", " + info.Location.countryName;

            HostnameResolver hr = new HostnameResolver(info.Address);
            hr.HostnameResolvedEvent += new HostnameResolver.HostNameResolvedHandler(AddressResolved);

            info.Updated += new UpdateHandler(UpdateInfo);
            UpdateInfo();
        }

        private void UpdateInfo()
        {
            Action action = delegate()
            {
                processes.Items.Clear();
                ulong packets = 0;
                ulong data = 0;
                foreach (KeyValuePair<ushort, ProcessInfo> entry in info.GetProcessInfoList())
                {
                    string procName = "unknown";
                    if (entry.Value.Process != null)
                        procName = entry.Value.Process.ProcessName;
                    packets += entry.Value.Packets;
                    data += entry.Value.Data;
                    ListViewItem item = new ListViewItem(new string[] {
                        procName,
                        entry.Key.ToString(),
                        entry.Value.Protocol.ToString(),
                        entry.Value.Data.ToString(),
                        new DataRepresenter().represent(entry.Value.Data)
                    });
                    processes.Items.Add(item);
                }
                packetsLbl.Text = packets.ToString();
                dataLbl.Text = new DataRepresenter().represent(data);
            };

            // Ensure we call in creator thread!
            if (InvokeRequired)
            {
                Invoke(new MethodInvoker(action));
            }
            else
            {
                action();
            }
        }

        private void AddressResolved(string hostname)
        {
            hostnameLbl.Text = hostname;
        }

        private void traceRouteBtn_Click(object sender, EventArgs e)
        {
            if (TraceRouteEvent != null)
                TraceRouteEvent(info.Address);
        }
    }
}
